package com.ciwong.epaper.modules.otherlogin;

import android.content.Intent;
import android.util.Log;

import com.ciwong.epaper.modules.otherlogin.bean.QQLoginParam;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

/**
 * 此类实现QQ登录授权相关操作 Created by res-dlzhou on 2015/9/2.
 */
public abstract class QQLoginAction extends WeixinLoginAction
        implements IUiListener
{
    /**
     * QQAPI
     */
    private Tencent mTencent;

    /**
     * QQ登录授权动作(调用此方法启动第三方登录授权,授权成功后，三个月后才须要授权)
     */
    public void loginWithQQAction()
    {
        loginWithQQAction(true);
    }

    /**
     * QQ登录授权动作(调用此方法启动第三方登录授权)
     * 
     * @param reLogin
     *            false为每次获授权
     */
    public void loginWithQQAction(boolean reLogin)
    {
        if (mTencent == null)
        {
            mTencent = Tencent.createInstance(getLoginConfig().getQQAppID(),
                    mActivity);
        }
        QQLoginParam loginParam = mParamSharedUtil.getQQLoginParam();
        // 授权信息可用直接登录
        if (loginParam != null && !mParamSharedUtil.isQQLoginExpires()
                && reLogin)
        {
            dealWithQQLoginParamInfo(loginParam, null);
        }
        else
        {
            // 重新授权
            if (!mTencent.isSessionValid())
            {
                mTencent.login(mActivity, "all", this);
            }
        }
    }

    /**
     * 回收资源
     */
    protected void releaseTencent()
    {
        if (mTencent != null)
        {
            mTencent.releaseResource();
            mTencent = null;
        }
    }

    /**
     * QQ回调结果方法，须在activity,onActivityResult方法内调用
     * 
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResultData(int requestCode, int resultCode,
            Intent data)
    {
        Tencent.onActivityResultData(requestCode, resultCode, data, this);
        if (requestCode == Constants.REQUEST_API)
        {
            if (resultCode == Constants.REQUEST_LOGIN)
            {
                Tencent.handleResultData(data, this);
            }
        }
    }

    @Override
    public void onComplete(Object response)
    {
        if (response != null)
        {
            Log.d("Otherlogin", "QQjSON:" + response.toString());
            try
            {
                JSONObject jsonObject = (JSONObject) response;
                QQLoginParam qqLoginParam = new QQLoginParam();
                qqLoginParam.setExpires_in(
                        jsonObject.getString(Constants.PARAM_EXPIRES_IN));
                qqLoginParam.setAccess_token(
                        jsonObject.getString(Constants.PARAM_ACCESS_TOKEN));
                qqLoginParam.setOpenid(
                        jsonObject.getString(Constants.PARAM_OPEN_ID));
                qqLoginParam.setRet(jsonObject.getInt("ret"));

                if (qqLoginParam != null && qqLoginParam.getRet() == 0)
                {
                    // 保存QQ登录信息
                    mParamSharedUtil.setQQLoginParam(qqLoginParam);
                    dealWithQQLoginParamInfo(qqLoginParam, response);
                }
                else
                {
                    mListener.onLoginError(LoginType.QQ, 1000, "响应出错!");
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                mListener.onLoginError(LoginType.QQ, 1000, "数据解析错误");
            }
        }
        else
        {
            mListener.onLoginError(LoginType.QQ, 1000, "登录授权响应数据为null");
        }
    }

    @Override
    public void onError(UiError uiError)
    {
        mListener.onLoginError(LoginType.QQ, uiError.errorCode,
                uiError.errorMessage);
    }

    @Override
    public void onCancel()
    {
        mListener.onLoginCancel();
    }

    /**
     * 处理qq登录信息
     * 
     * @param qqLogin
     * @param response
     */
    private void dealWithQQLoginParamInfo(QQLoginParam qqLogin, Object response)
    {
        mTencent.setOpenId(qqLogin.getOpenid());
        mTencent.setAccessToken(qqLogin.getAccess_token(),
                qqLogin.getExpires_in());
        mListener.onLoginComplete(LoginType.QQ, qqLogin);
        logoutLogin();
        Log.d("login", "QQToken:" + qqLogin.getAccess_token());
    }

    /**
     * 注销登录
     */
    private void logoutLogin()
    {
        mTencent.logout(mActivity);
    }

}
